package cn.com.pc.penguin.builder.keyword;

import cn.com.pc.penguin.service.DocumentBuilder;
import cn.com.pc.penguin.service.SearchType;
import cn.com.pc.penguin.service.impl.SearchTypes;
import cn.com.pc.penguin.utils.StringUtil;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

public class KeywordDocumentBuilder implements DocumentBuilder {

	private List<Keyword> keywords;
	
	public KeywordDocumentBuilder(List<Keyword> searchKeywords) {
		this.keywords = searchKeywords;
	}
	
	public SearchType getSearchType() {
		return SearchTypes.KEYWORD;
	}
	
    public List<Document> getDocs() throws Exception {
        List<Document> docs = new ArrayList<Document>();
        try{
        	for(Keyword ss : keywords) {
    	    	try {    	    		
    	    		Document doc = new Document();
    	    		doc.add(new Field(KeywordSearchFields.Keyword.ID, ss.getKeyword(), Field.Store.YES,
            				Field.Index.NOT_ANALYZED));

    	    		doc.add(new Field(KeywordSearchFields.Keyword.KEYWROD_UNTOKENIZIED, ss.getKeyword().toLowerCase(), Field.Store.NO,
            				Field.Index.NOT_ANALYZED));
    	    		
    	    		doc.add(new Field(KeywordSearchFields.Keyword.KEYWORD_PINYIN, StringUtil.getPinYin(ss.getKeyword()), Field.Store.NO,
            				Field.Index.NOT_ANALYZED));

                    doc.add(new Field(KeywordSearchFields.Keyword.KEYWORD_PINYIN_HEAD, StringUtil.getPinYinHead(ss.getKeyword()), Field.Store.NO,
                                                Field.Index.NOT_ANALYZED));
    	    		
    	    		doc.add(new Field(KeywordSearchFields.Keyword.SEACHES, String.valueOf(ss.getSearches()), Field.Store.YES,
            				Field.Index.NOT_ANALYZED));
    	    		
    	    		doc.add(new Field(KeywordSearchFields.Keyword.RESULT, String.valueOf(ss.getResult()), Field.Store.YES,
            				Field.Index.NOT_ANALYZED));
    	    		
    	    		doc.add(new Field(KeywordSearchFields.Index.KEYWROD, ss.getKeyword(), Field.Store.NO,
            				Field.Index.ANALYZED)); 
    	    		
    	    		docs.add(doc);
    	    	}catch(Exception e) {
    	    		e.printStackTrace();
    	    	}
    	    }
        
        }catch(Exception e){
            e.printStackTrace();
        }
        return docs;
    }

	public Collection<String> getKeys() throws Exception {
	    List<String> keys = new ArrayList<String>();
	    for(Keyword ss : keywords) {
	    	keys.add(ss.getKeyword());
	    }
        return keys;
	}	
}
